<!--
基本信息--使用elelmentuiplus
-->

<template>
  <div>
    <el-row>
      <el-col :span="24">
        <div>
          <div style="display: flex;justify-content: right">
<!--            <el-button  type="primary"  @click="handleExport('导出数据','#singleTab',{ raw: true })">导出标的</el-button>-->
            <el-upload  action="#"  :show-file-list="false" :before-upload="handBdImport" accept=".xls,.xlsx"
                        style="margin: 0 12px;display: flex;align-items: center;">
              <el-button type="success" >导入标的</el-button>
            </el-upload>

            <el-button type="primary"  @click="addOneTable" >新增一行</el-button>
          </div>
          <div style="width: 100%">
            <vxe-table
                ref="xTable"
                id="singleTab"
                class="mytable-scrollbar"
                border
                show-overflow
                show-header-overflow
                show-footer-overflow
                height="600"
                maxHeight="600"
                keep-source
                :scrollbarConfig="{x: {position: 'top'}}"
                :data="state.table.data"
                :size="'mini'"
                :column-config="{resizable: true}"
                :virtual-y-config="{enabled: true, gt: 0}"
            >
              <vxe-column field="LineNum" title="行号" width="60" fixed="left"></vxe-column>

              <vxe-column field="CinvCode" title="存货编码" width="130">
                <template #default="{ row }">
                  <el-select
                      v-model="row.CinvCode"
                      filterable
                      remote
                      reserve-keyword
                      :disabled="!row.IsJS && (row.Id )"
                      placeholder="请选择存货"
                      :remote-method="query => remoteMethod(query, row)"
                      :loading="state.loading"
                      @change="(e) => updateInv(e, row)"
                      size="small"
                      style="width: 100%"
                  >
                    <el-option
                        v-for="item in state.options"
                        :key="item.cInvCode"
                        :label="item.cInvCode"
                        :value="item.cInvCode"
                    >
                      <span style="float: left">{{ item.cInvName }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">
                    {{ item.cInvCode }}
                  </span>
                    </el-option>
                  </el-select>
                </template>
              </vxe-column>

              <vxe-column field="CinvName" title="存货名称" width="200"></vxe-column>
              <vxe-column field="Unit" title="单位" width="60"></vxe-column>

              <vxe-column field="CustCinvCode" title="合同序号" width="80">
                <template #default="{ row }">
                  <el-input
                      v-model="row.CustCinvCode"
                      :disabled="!row.IsJS && (row.Id )"
                      placeholder="请输入合同序号"
                      size="small"
                      style="width: 100%"
                      filterable clearable />
                </template>
              </vxe-column>

              <vxe-column field="CustCinvName" title="客户存货名称" width="220">
                <template #default="{ row }">
                  <el-input
                      v-model="row.CustCinvName"
                      :disabled="!row.IsJS && (row.Id )"
                      placeholder="请输入客户存货名称"
                      size="small"
                      style="width: 100%"
                      filterable clearable />
                </template>
              </vxe-column>

              <vxe-column field="CustCinvAdd" title="客户存货规格" width="220"></vxe-column>

              <vxe-column field="JFDate" title="交付时间" width="140">
                <template #default="{ row }">
                  <el-date-picker
                      v-model="row.JFDate"
                      type="date"
                      placeholder="请选择交付时间"
                      format="YYYY-MM-DD"
                      :disabled="!row.IsJS && (row.Id )"
                      value-format="YYYY-MM-DD"
                      :disabled-date="disabledDate"
                      clearable
                      size="small"
                      style="width: 100%"
                  />
                </template>
              </vxe-column>

              <vxe-column field="Price" title="含税单价" width="120">
                <template #default="{ row, rowIndex }">
                  <el-input
                      v-model="row.Price"
                      placeholder="请输入含税单价"
                      :disabled="!row.IsJS && (row.Id )"
                      clearable
                      @change="(e)=>numChange(e, row, rowIndex)"
                      size="small"
                      style="width: 100%"
                  />
                </template>
              </vxe-column>

              <vxe-column field="Quantity" title="数量" width="120">
                <template #default="{ row, rowIndex }">
                  <el-input
                      v-model="row.Quantity"
                      placeholder="请输入数量"
                      clearable
                      :disabled="!row.IsJS && (row.Id )"
                      @change="(e)=>numChange(e, row, rowIndex)"
                      size="small"
                      style="width: 100%"
                  />
                </template>
              </vxe-column>

              <vxe-column field="Amount" title="价税合计" width="110"></vxe-column>

              <vxe-column field="Rate" title="税率" width="120">
                <template #default="{ row, rowIndex }">
                  <el-input
                      v-model="row.Rate"
                      placeholder="请输入税率"
                      clearable
                      :disabled="!row.IsJS && (row.Id )"
                      @change="(e)=>numChange(e, row, rowIndex)"
                      size="small"
                      style="width: 100%"
                  />
                </template>
              </vxe-column>

              <vxe-column field="Tax" title="税额" width="110"></vxe-column>
              <vxe-column field="iNatPrice" title="无税单价" width="110"></vxe-column>
              <vxe-column field="iNatAmount" title="无税金额" width="110"></vxe-column>
              <vxe-column field="TDYSFile" title="通电验收文件" width="110"></vxe-column>
              <vxe-column field="FHTZDFile" title="交货验收文件" width="110"></vxe-column>
              <vxe-column field="JSDFile" title="结算资料" width="110"></vxe-column>
              <vxe-column field="YSaleQty" title="已下订单数量" width="120"></vxe-column>
              <vxe-column field="YSaleAmount" title="已下订单金额" width="120"></vxe-column>
              <vxe-column field="YFHQty" title="已发货数量" width="100"></vxe-column>
              <vxe-column field="YFHAmount" title="已发货金额" width="100"></vxe-column>
              <vxe-column field="YJSQty" title="已结算数量" width="100"></vxe-column>
              <vxe-column field="YJSAmount" title="已结算金额" width="100"></vxe-column>
              <vxe-column field="YFHYSQty" title="已发货验收数量" width="140"></vxe-column>
              <vxe-column field="YTDYSQty" title="已通电验收数量" width="140"></vxe-column>
              <vxe-column field="Remark" title="备注" width="140"></vxe-column>

              <vxe-column field="IsJS" title="据实结算" width="80" fixed="right">
                <template #default="{ row }">
                  <el-switch v-model="row.IsJS" disabled />
                </template>
              </vxe-column>

              <vxe-column field="RowState" title="状态" width="80" fixed="right">
                <template #default="{ row }">
                  <el-select
                      v-model="row.RowState"
                      filterable
                      :disabled="!row.IsJS && (row.Id )"
                      remote
                      reserve-keyword
                      placeholder="请选择状态"
                      remote-show-suffix
                      style="width: 100%"
                  >
                    <el-option label="正常" value="1"></el-option>
                    <el-option label="关闭" value="0"></el-option>
                  </el-select>
                </template>
              </vxe-column>

              <vxe-column title="操作" width="60" fixed="right">
                <template #default="{ rowIndex,row }">

                  <el-button type="primary" :disabled="!row.IsJS && (row.Id )" link @click="editDelT(rowIndex)">删除</el-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </el-col>
    </el-row>



  </div>
</template>

<script setup>
import {onMounted, ref, toRefs} from "vue";
import { GetInventory2,DetailImoprtExcel} from "@/api/base";
import { debounce, parseTime} from "@/utils/util";
import {ElMessage,} from "element-plus";
import { VxeTable, VxeColumn } from 'vxe-table'
import 'vxe-table/lib/style.css'

const emit = defineEmits(['submit',"update:SubList"])
defineOptions({ name: 'EntryBaseInfo' })
const props = defineProps({
  baseInfo: {
    type: Object,
    default: {}
  },
  subList: {
    type: Array,
    default: () => {
      return []
    }
  },
  Id:{
    type: String,
    default: ''
  },
})

let {
  baseInfo,
  subList,
  Id,
} = toRefs(props)

let formRef =ref({})


//定义数据
const state = reactive({
  options:[],
  table: {
    tableOptions: {
      widthMode: "auto",
      heightMode: "auto",
      defaultRowHeight: 40,
      rightFrozenColCount: 1,
    },
    busy:false,
    loadedData:[], // 已加载的数据
    border: true,
    rules: {
      CinvCode: [{ required: true, message: "请选择存货", trigger: "change" }],
      Unit: [{ required: true, message: "请输入单位", trigger: "blur" }],
      Price: [{ required: true, message: "请输入单价", trigger: "blur" }],
      Quantity: [{ required: true, message: "请输入数量", trigger: "blur" }],
      Amount: [{ required: true, message: "请输入总价", trigger: "blur" }]
    },
    // firstColumn: { type: "index", label: "行号",props:'LineNum' }, // 显示序列号
    data: [],
    columns: [
      {
        key: "LineNum",
        dataKey: "LineNum",
        title: "行号",
        width: 60,
        fixed: "left",
      },
      {
        key: "CinvCode",
        dataKey: "CinvCode",
        title: "存货编码",
        width: "130",
      },
      {
        key: "CinvName",
        dataKey: "CinvName",
        title: "存货名称",
        width: "200",
      },
      {
        key: "Unit",
        dataKey: "Unit",
        title: "单位",
        width: "60",
      },
      {
        key: "CustCinvCode",
        dataKey: "CustCinvCode",
        title: "合同序号",
        width: "80",
      },
      {
        key: "CustCinvName",
        dataKey: "CustCinvName",
        title: "客户存货名称",
        width: "220",
      },
      {
        key: "CustCinvAdd",
        dataKey: "CustCinvAdd",
        title: "客户存货规格",
        width: "220",
      },
      {
        key: "JFDate",
        dataKey: "JFDate",
        title: "交付时间",
        width: "140",
      },
      {
        key: "Price",
        dataKey: "Price",
        title: "含税单价",
        width: "120",
      },
      {
        key: "Quantity",
        dataKey: "Quantity",
        title: "数量",
        width: "120",
      },
      {
        key: "Amount",
        dataKey: "Amount",
        title: "价税合计",
        width: "110",
      },
      {
        key: "Rate",
        dataKey: "Rate",
        title: "税率",
        width: "120",
      },
      {
        key: "Tax",
        dataKey: "Tax",
        title: "税额",
        width: "110",
      },
      {
        key: "iNatPrice",
        dataKey: "iNatPrice",
        title: "无税单价",
        width: "110",
      },
      {
        key: "iNatAmount",
        dataKey: "iNatAmount",
        title: "无税金额",
        width: "110",
      },

      {
        key: "TDYSFile",
        dataKey: "TDYSFile",
        title: "通电验收文件",
        width: "110",
      },
      {
        key: "FHTZDFile",
        dataKey: "FHTZDFile",
        title: "交货验收文件",
        width: "110",
      },
      {
        key: "JSDFile",
        dataKey: "JSDFile",
        title: "结算资料",
        width: "110",
      },
      {
        key: "YSaleQty",
        dataKey: "YSaleQty",
        title: "已下订单数量",
        width: "120",
      },
      {
        key: "YSaleAmount",
        dataKey: "YSaleAmount",
        title: "已下订单金额",
        width: "120",
      },
      {
        key: "YFHQty",
        dataKey: "YFHQty",
        title: "已发货数量",
        width: "100",
      },
      {
        key: "YFHAmount",
        dataKey: "YFHAmount",
        title: "已发货金额",
        width: "100",
      },
      {
        key: "YJSQty",
        dataKey: "YJSQty",
        title: "已结算数量",
        width: "100",
      },
      {
        key: "YJSAmount",
        dataKey: "YJSAmount",
        title: "已结算金额",
        width: "100",
      },
      {
        key: "YFHYSQty",
        dataKey: "YFHYSQty",
        title: "已发货验收数量",
        width: "140"
      },{
        key: "YTDYSQty",
        dataKey: "YTDYSQty",
        title: "已通电验收数量",
        width: "140"
      },
      {
        key: "Remark",
        dataKey: "Remark",
        title: "备注",
        width: "140",
      },
      {
        key: "RowState",
        dataKey: "RowState",
        title: "状态",
        width: 80,
        fixed:'right'
      },
      {
        key: "operatorT",
        dataKey: "operatorT",
        title: "操作",
        width: 60,
        fixed:'right'
      }
    ],

    exportConfig: [ // 导出Excel表格配置
      {
        title: '*序号',
        key: 'LineNum',
        type: 'text'
      },
      {
        title: '存货编码',
        key: 'CinvCode',
        type: 'text'
      },
        {
          title: '*产品名称',
          key: 'CinvName',
          type: 'text'
        },

        {
          title: '*单位',
          key: 'Unit',
          type: 'text'
        },
        {
          title: '*合同序号',
          key: 'CustCinvCode',
          type: 'text'
        },
        {
          title: '*合同名称',
          key: 'CustCinvName',
          type: 'text'
        },
        {
          title: '*合同型号',
          key: 'CustCinvAdd',
          type: 'text'
        },
        {
          title: '*单价',
          key: 'Price',
          type: 'text'
        },
        {
          title: '*数量',
          key: 'Quantity',
          type: 'text'
        },
        {
          title: '税率',
          key: 'Rate',
          type: 'text'
        },
        {
          title: '标记(新增不填)',
          key: 'Id',
          type: 'text'
        },
        {
          title: '交货日期',
          key: 'JFDate',
          type: 'date'
        },
      {
        title: '备注信息',
        key: 'Remark',
        type: 'text'
      },

      {
        title: '变更原因',
        key: 'BgRemark',
        type: 'text'
      },

    ],
  },
  //存货下拉
  invList :[]
})


// 数量change事件
const numChange = (val, prop, index) => {
  let rate = (state.table.data[index].Rate /100) + 1
  state.table.data[index].Amount= (Number(state.table.data[index].Quantity || 0) * Number(state.table.data[index].Price || 0)).toFixed(2)//含税金额
  state.table.data[index].iNatPrice=(Number(state.table.data[index].Price || 0) / rate).toFixed(5)//不含税单价=含税单价 / 1.13

  state.table.data[index].Tax=( (state.table.data[index].Amount || 0) - ((state.table.data[index].Amount || 0) / rate)).toFixed(2)//税额
  state.table.data[index].iNatAmount=((state.table.data[index].Amount || 0 ) - state.table.data[index].Tax).toFixed(2)//不含税金额 = 含税金额 * 1.13

  //计算合同金额
  console.log(state.table.data,"1212")

  let reduce = state.table.data.reduce((acc, cur) => {
    return acc + (Number(cur.Amount) || 0);
  }, 0);
  console.log(reduce,"1212")

  baseInfo.value.ContractAmount =Number(reduce)

  state.tableZfBz.data.forEach(item=>{
    if (item.Ratio){
      item.Amount = (Number(reduce) * (Number(item.Ratio)/100)).toFixed(2)
    }
  })
}


const editDelT = (index) => {
  state.table.data.splice(index, 1)
}


onMounted(() => {
  state.table.data = subList.value?subList.value:[];
})



const xTable = ref(null)
function handleExport(fileName='',idName = "#singleTab",xlsxParam={ raw: true }){
  const $table = xTable.value
  if ($table) {
    $table.exportData({
      type: 'xlsx'
    })
  }
}

async function handBdImport(file) {
  let res = await DetailImoprtExcel({file: file})
  if (res.Code ===  "Error") {
    ElMessage.error({
      message: res.Result,
      duration: 10000,
      showClose: true
    });
    return;
  }

  state.table.data=res.Data?.SubList
  emit('update:SubList', state.table.data)
}




function  addOneTable () {
  let maxLineNum = 0;
  if (state.table.data.length > 0) {
    maxLineNum = Math.max(...state.table.data.map(item => item.LineNum || 0));
  }
  state.table.data.push({
    //获取最大行号加1
    LineNum: maxLineNum + 1,
    Amount: null,
    Quantity: null,
    Price: [],
    Unit: null,
    CinvName: null,
    CinvCode: null,
    IsJS: true,
    RowState:"1",
    Rate: props.baseInfo.Rate,
  })
}

//存货选择
function updateInv(e,row){

  //过滤客户
  let invoptions = state.invList.filter((its) => {
    return (its.cInvCode.toLowerCase().includes(e.toLowerCase()))
  })[0]
  if (invoptions){
    //赋值
    row.CinvName = invoptions.cInvName
    row.Unit = invoptions.CComUnitName
  }

}

// 获取文件名称
function getFileStatus(files) {
  // 判断list中FileAdd是否都有值，全部有值返回完整，部分返回部分上传
  if (!Array.isArray(files) || files.length === 0) {
    return '无文件';
  }

  const allHaveValues = files.every(file => file.FileAdd !== undefined && file.FileAdd !== null && file.FileAdd !== '');
  const someHaveValues = files.some(file => file.FileAdd !== undefined && file.FileAdd !== null && file.FileAdd !== '');

  if (allHaveValues) {
    return 'Y';
  } else if (someHaveValues) {
    return 'B';
  } else {
    return 'N';
  }
}

function hasCheck(name){
  const phasedFile = props.baseInfo?.PhasedFile || [];

  if (phasedFile!==undefined && phasedFile.length>0){
    let b = phasedFile.some(item => item.includes(name));
    return b>0;

  }
  else
    return false;
}

//查询存货 -- 增加防抖函数
const remoteMethod = debounce(async (query) => {
  if (query) {
    state.loading = true
    state.loading = false

    let invData = {
      Code: query,
    }
    let {Data} = await GetInventory2(invData)
    state.invList = Data
    state.options = state.invList.filter((item) => {
      return (item.cInvName.toLowerCase().includes(query.toLowerCase()) || item.cInvCode.toLowerCase().includes(query.toLowerCase()))
    })
  } else {
    state.options = []
  }
},200,false)


const disabledDate = (time) => {
  return time.getTime() < Date.now() - 8.64e7; // 禁用今天之前的日期
};


defineExpose({formRef})

</script>

<style scoped lang="scss">

.el-form-item {
  --font-size: 12px;
  --el-form-label-font-size: var(--font-size);
  margin-bottom: 2px!important;
}

/* 隐藏未加载的行 */
:deep(.hidden-row) {
  display: none;
}

</style>

<style lang="scss">

.mytable-scrollbar {
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 4px;
  }
}


/** 默认模式 */
[data-vxe-ui-theme="light"] {
  .mytable-scrollbar {
    ::-webkit-scrollbar-track,
    ::-webkit-scrollbar-corner {
      background-color: #FFFFFF;
    }
    ::-webkit-scrollbar-thumb {
      background-color: #bfbfbf;
    }
    ::-webkit-scrollbar-thumb:hover,
    ::-webkit-scrollbar-thumb:active {
      background-color: #787878;
    }
  }
}

/** 暗黑模式 */
[data-vxe-ui-theme="dark"] {
  .mytable-scrollbar {
    ::-webkit-scrollbar-track,
    ::-webkit-scrollbar-corner {
      background-color: #151518;
    }
    ::-webkit-scrollbar-thumb {
      background-color: #bfbfbf;
    }
    ::-webkit-scrollbar-thumb:hover,
    ::-webkit-scrollbar-thumb:active {
      background-color: #A3A6AD;
    }
  }
}
</style>
